package simkuenzi.catchme;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.renderscript.Int4;
import android.os.Handler;

public class GameActivity extends Activity {

	private Game game;
	private	Handler changeHandler = new Handler();
	float z;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		final TextView text = (TextView) findViewById(R.id.text);

		final View view = new View(this){
			protected void onDraw(Canvas canvas) {
				drawObject(canvas, Color.YELLOW, game.getTarget());
				drawObject(canvas, Color.RED, game.getPlayer());

			}
			protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
				if (changed) {
					game.setWidth(right - left);
					game.setHeight(bottom - top);
				}
			}
		};
		SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		Sensor accl = sm.getDefaultSensor(Sensor.TYPE_GRAVITY);
		sm.registerListener(new SensorEventListener() {

				public void onSensorChanged(SensorEvent se) {
					game.control(se.values[0], se.values[1]);
					z = se.values[0] / se.values[1];
				}

				public void onAccuracyChanged(Sensor p1, int p2) {
					// TODO: Implement this method
				}


			} , accl, SensorManager.SENSOR_DELAY_FASTEST);

		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);

		layout.addView(view);

		game = Game.createDefault();
		game.addListener(new GameListener(){

				public void changed() {
					Runnable r =new Runnable() {
						public void run() {
							view.invalidate();
							if (game.isSuccess()) {
								text.setText("Geschafft!!");
							}
//							text.setText(Float.toString(z));
						}
					};

					changeHandler.post(r);
				}

			});
    }

	protected void onResume() {
		super.onResume();
		game.run();
	}

	protected void onPause() {
		super.onPause();
		game.pause();
	}
	private static void drawObject(Canvas canvas, int color, GameObject o) {
		Paint paint = new Paint();
		paint.setStyle(Paint.Style.FILL);
		paint.setColor(color);
		canvas.drawRect(o.getX(), o.getY(), o.getX() + o.getSize(), o.getY() + o.getSize(), paint);
	}
}
